#!/bin/bash
# Script to del Virtual users from the VSFTPD server
# Author Bellamkonda Sudhakar
# Version 0.2
#
#config file /etc/vsftpd/vuser/vuser.conf
#
. /etc/vsftpd/vuser/vuser.conf
VUFLAG=0
VUSER=$1
VUSER_BAK=$VUSER_DEL_BAK.`date +%d%m%Y`
#VUSER_BAK=$VUSER_DEL_BAK.`date +%d%m%Y-%H%m%S`
VDELFILE=$CONFIG_ROOT/$VUSER_DEL
#
echo; echo
#
if [ $UID != "0" ]
then
echo "Not root, Exiting"
echo
exit 1
fi
#
if [ -z "$1" ]
then
echo "Usage: $0 <username>"
echo
exit 1
fi
#
if [ -n "`grep $1 $CONFIG_ROOT/$VUSER_LIST`" ]
then
  echo "User $1 exists"
  VUFLAG=1
fi
#
if [ -d $VUSER_HOME/$1 ]
then
  echo "Folder $VUSER_HOME/$1 exists"
  VUFLAG=1
fi
#
if [ $VUFLAG -eq 1 ]
then 
echo "$VUSER occures `grep -c $VUSER $CONFIG_ROOT/$VUSER_LIST` times in user file"
#
gawk -v VUSER=${VUSER} -v VTMP=${VTMP} 'BEGIN { print "Extracting Password for user "VUSER" from user text file..." }
   $1 ~ VUSER { print $0 > VTMP
              getline   
              print $0 >> VTMP }
   END { print "User and Password pairs added to "VTMP }' $CONFIG_ROOT/$VUSER_LIST
#
echo "Backing up current vuser_list to $VUSER_BAK"
cp $CONFIG_ROOT/$VUSER_LIST $CONFIG_ROOT/$VUSER_BAK
#
echo "Adding user to $VUSER_DEL File"
cat $VTMP >> $CONFIG_ROOT/$VUSER_DEL
for t in `sort -b -r -u $VTMP`
do
   sed -i '/'$t'/d' $CONFIG_ROOT/$VUSER_LIST > /dev/null
done
echo "User deleted from list file, generating DB..."
db_load -T -t hash -f $CONFIG_ROOT/$VUSER_LIST $CONFIG_ROOT/$VUSER_DB.db
echo "Renaming Home folder to $VUSER-deleted for user $VUSER at $VUSER_HOME"
mv $VUSER_HOME/$VUSER $VUSER_HOME/$VUSER-deleted
echo "Cleaning Up..."
rm -f $VTMP
echo "Done."
fi
echo; echo
